﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web.Mvc;
using Castle.Core;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Equation.Enterprise.Framework.Web;
using Equation.Enterprise.Framework.Web.Controller;

namespace Equation.Enterprise.Framework.Windsor
{
    public static class WindsorExtensions
    {
        public static IWindsorContainer RegisterController<T>(this IWindsorContainer container) where T:IController
        {
            container.RegisterControllers(typeof(T));
            return container;
        }

        public static IWindsorContainer RegisterControllers(this IWindsorContainer container, params Type[] controllerTypes)
        {
            foreach(var type in controllerTypes)
                if (ControllerExtensions.IsController(type))
                    container.Register(Component.For(type).Named(type.FullName.ToLower()).LifeStyle.Is(LifestyleType.Transient));

            return container;
        }

        public static IWindsorContainer RegisterControllers(this IWindsorContainer container, params Assembly[] assemblies)
        {
            foreach (var assembly in assemblies)
                container.RegisterControllers(assembly.GetExportedTypes());

            return container;
        }

        public static IWindsorContainer RegisterFromInterface(this IWindsorContainer container, Type interfaceType, params Assembly[] assemblies)
        {
            foreach (var assembly in assemblies)
                container.Register(AllTypes.FromAssembly(assembly).Pick()
                                     .WithService.FromInterface(interfaceType)
                                     .Configure(o => o.LifeStyle.Is(LifestyleType.Transient)));

            return container;
        }
    }
}
